#!/usr/bin/env python
import os, sys, random
import urllib

if os.environ.has_key("QUERY_STRING"):
    print "Content-Type: text/html"
    print 
    import cgitb; cgitb.enable()

import ConfigParser, os
cfg = ConfigParser.ConfigParser()
#cfg.read(os.path.join(os.environ["HOME"], ".yoshiiibox.ini"))
cfg.read("/etc/yoshiiibox.ini")
local_prefix 	= cfg.get("gallery", "local_prefix") # path to images on disk e.h. /home/username/public_html
web_prefix   	= cfg.get("gallery", "web_prefix")	  # path on the webserver e.g. /~username
photo_dir	= cfg.get("gallery", "photo_dir")	  # dir on the webserver and disk e.g. gallery_images
thumb_dir	= cfg.get("gallery", "thumb_dir")
thumb_height	= int(cfg.get("gallery", "thumb_height"))

website		= """\
    <html>
	<head>
	    <link rel="stylesheet" type="text/css" href="%(css_location)s">
	    <title>gallery</title>
	</head>
	<body>
	    %(body)s
	</body>
    </html>"""

navigation	= """\
<script type="text/javascript">
function KeyPressed (Event) {
 if (!Event)
    Event = window.event;
    if (Event.keyCode == 39) {
	location.href = "%(next)s";
    } else if (Event.keyCode == 38) {
        location.href = "%(index)s";
    } else if (Event.keyCode == 37) {
        location.href = "%(previous)s";
    } <!---else alert(Event.keyCode);--->
}
document.onkeypress = KeyPressed;
</script>
"""

css_location	= os.path.join(web_prefix, "gallery.css")
single_photo	= '<a href=%(next)s><img src="%(current)s "/></a><br><br><a href=%(previous)s>&lt;</a> <a href=%(index)s>o</a> <a href=%(next)s>&gt;</a>\n'
gallery_item	= '<a href=%(next)s><img src="%(current)s" height=%(height)s hspace=2 vspace=2 /></a>\n'
endl		= "<br>\n"


def time_sorted_files(path, ext):
    import os, time
    all_fnames = filter(lambda x:x.lower().endswith(ext), os.listdir(path))
    sorted_names = sorted([(os.stat(os.path.join(path, fname))[os.path.stat.ST_MTIME], fname) for fname in all_fnames])
    sorted_names.reverse()
#    print sorted_names
    return [name for time, name in sorted_names]

def generate_thumbs():
    import Image
    for fname in filter(lambda x:x.endswith(".jpg"), os.listdir(os.path.join(local_prefix, photo_dir))):
	if not os.path.exists( os.path.join(local_prefix, thumb_dir, fname) ):
	    os.system("chmod +r %s"%os.path.join(local_prefix, photo_dir, fname))
	    img = Image.open(os.path.join(local_prefix, photo_dir, fname))
	    ih, iw = img.size
	    th, tw = (int(float(ih) / iw * thumb_height), thumb_height )
	    print "generating thumb", fname
	    thumb = img.resize( (th, tw), Image.ANTIALIAS)
	    thumb.save(os.path.join(local_prefix, thumb_dir, fname))

def prepare_gallery():
    gal = ""
    first = None
    last = None
#    for fname in os.listdir(os.path.join(local_prefix, photo_dir)):
    for fname in time_sorted_files(os.path.join(local_prefix, photo_dir), ".jpg"):
	next    = os.environ["SCRIPT_NAME"] + "?" + fname
	if not os.path.exists(os.path.join(local_prefix, thumb_dir, fname)):
	    try:
		generate_thumbs()
	    except:
		pass
	if os.path.exists(os.path.join(local_prefix, thumb_dir, fname)):
	    current = os.path.join(web_prefix, thumb_dir, fname)
	else:
	    current = os.path.join(web_prefix, photo_dir, fname)
	gal += gallery_item%{"current":current, "next":next, "height":thumb_height}

	if first == None: first = next
	last = next

    ## prepare navigation
    index = os.environ["SCRIPT_NAME"]
    nav = navigation%{"previous":last, "next":first, "index":index } + endl

    return nav + endl + gal

def prepare_single(img):
    current = os.path.join(web_prefix, photo_dir, img)
    index = os.environ["SCRIPT_NAME"]

#    all = os.listdir(os.path.join(local_prefix, photo_dir))
    all = time_sorted_files(os.path.join(local_prefix, photo_dir), ".jpg")
    this_idx = all.index(img)

    if this_idx > 0:
	previous = os.environ["SCRIPT_NAME"] + "?" + all[this_idx-1]
    else:
	previous = os.environ["SCRIPT_NAME"]

    if this_idx + 1 < len(all):
	next = os.environ["SCRIPT_NAME"] + "?" + all[this_idx+1]
    else:
	next = os.environ["SCRIPT_NAME"]
    
    nav = navigation%{"previous":previous, "next":next, "index":index } + endl
    pic = single_photo%{"previous":previous, "current":current, "next":next, "index":index} + endl
    return nav + endl + pic

def cgi_main():
    body = ""
    #body += "query string=" + repr(os.environ["QUERY_STRING"]) + endl
    #body += "query string=" + repr(os.environ["SCRIPT_NAME"]) + endl
    #body += repr(os.environ) + endl

    if os.environ["QUERY_STRING"] == "":
	body += prepare_gallery()
    else:
	body += prepare_single(os.environ["QUERY_STRING"])

    print website%{"body":body, "css_location":css_location}


if __name__ == '__main__':
    if os.environ.has_key("QUERY_STRING"):
	cgi_main()
    else:
	generate_thumbs()
